package xyz.shenmegui.foodcheckserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xyz.shenmegui.foodcheckserver.DO.Food;
import xyz.shenmegui.foodcheckserver.mapper.FoodMapper;
import xyz.shenmegui.foodcheckserver.service.FoodService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
@Transactional
public class FoodServiceImpl implements FoodService {

    @Autowired
    private FoodMapper foodMapper;

    @Override
    public Map searchFoodByName(String name) {
        QueryWrapper<Food> foodQueryWrapper = new QueryWrapper<Food>();
        foodQueryWrapper.like("fname", name);
        // 从数据库里查询， fname like '%name%' 的数据
        List<Food> foods = foodMapper.selectList(foodQueryWrapper);
        if(foods.size() > 0) {
            for (Food food:foods) {
                int nums = food.getFnums() + 1;
                food.setFnums(nums);
                foodMapper.updateById(food);
            }
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("data", foods);
        return map;
    }

    @Override
    public List<Food> searchFoodListByName(String name) {
        QueryWrapper<Food> foodQueryWrapper = new QueryWrapper<Food>();
        foodQueryWrapper.like("fname", name);
        // 从数据库里查询， fname like '%name%' 的数据
        List<Food> foods = foodMapper.selectList(foodQueryWrapper);
        if(foods.size() > 0) {
            for (Food food:foods) {
                int nums = food.getFnums() + 1;
                food.setFnums(nums);
                foodMapper.updateById(food);
            }
        }
        return  foods;
    }

    @Override
    public Food getFoodById(Integer id) {
        return foodMapper.selectById(id);
    }

    @Override
    public List<Food> selectTop10() {
        LambdaQueryWrapper<Food> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Food::getFnums);
        queryWrapper.last("limit 10");
        return foodMapper.selectList(queryWrapper);
    }

    @Override
    public int updateOrFoods(List<Food> foods) {
        return 0;
    }
}
